<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-10-24 10:47:19
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-01-04 10:25:27
 * @FilePath: /hr_new_vue3/src/views/Management/Human/ChangeManagement/LeaveManagement/WaitLeave/Components/LeaveInterView/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 发起离职面谈 -->
<template>
  <ContentCard class="wrap">
    <template #header>
      <pageHeaderNew title="发起离职面谈" showBack></pageHeaderNew>
    </template>
    <main>
      <header>
        <a-steps changeable :current="currStep" @change="setCurrent">
          <a-step>面谈基础信息</a-step>
          <a-step>编辑面谈记录表 </a-step>
          <a-step>确认发起</a-step>
        </a-steps>
      </header>

      <section v-show="currStep === 1 || currStep === 3">
        <a-form
          autoLabelWidth
          :model="formData.step1Data"
          :rules="rules"
          ref="refForm"
        >
          <a-form-item label="面谈名称" showColon field="name">
            <a-input
              v-model="formData.step1Data.name"
              :disabled="currStep === 3"
            />
          </a-form-item>
          <a-form-item label="被面谈人" showColon field="userName">
            <a-input
              v-model="formData.step1Data.userName"
              disabled
              placeholder="系统自动读取离职人员"
            />
          </a-form-item>
          <a-form-item label="面谈负责人" showColon field="responsibleId">
            <a-select
              placeholder="请选择"
              allow-search
              allow-clear
              @popup-visible-change="showHumanModal"
              :popup-visible="false"
              v-model="formData.step1Data.responsibleId"
              :disabled="currStep === 3"
            >
              <a-option
                v-for="item in humanList"
                :value="item.id"
                :key="item.id"
                :label="item.name"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="面谈时间" showColon field="talkTime">
            <a-date-picker
              show-time
              format="YYYY-MM-DD HH:mm"
              v-model="formData.step1Data.talkTime"
              placeholder="请选择面谈时间"
              :disabled="currStep === 3"
            />
          </a-form-item>
          <a-form-item label="面谈地点" showColon field="talkSpace">
            <a-input v-model="formData.step1Data.talkSpace" />
          </a-form-item>
          <a-form-item
            label="选择离职面谈记录表模板"
            showColon
            field="templateId"
          >
            <a-select
              placeholder="请选择"
              allow-search
              allow-clear
              v-model="formData.step1Data.templateId"
              :disabled="currStep === 3"
            >
              <a-option
                v-for="item in leaveInterViewList"
                :value="item.id"
                :key="item.id"
                :label="item.name"
              >
                <template #label>
                  <div>
                    <div>{{ item.name }}</div>
                    <div>{{ item.scope === 1 ? '审核中' : '审核后' }}</div>
                  </div>
                </template>
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="备注" showColon field="remark">
            <a-textarea
              v-model="formData.step1Data.remark"
              showWordLimit
              :maxLength="300"
              :autoSize="{
                minRows: 3
              }"
              :disabled="currStep === 3"
            />
          </a-form-item>
        </a-form>

        <!-- <a-space v-show="currStep === 3" class="btn" size="large">
          <a-button @click="router.go(-1)">取消</a-button>
          <a-button type="primary" @click="save">保存</a-button>
          <a-button type="primary" @click="send">确认发送</a-button>
        </a-space> -->
      </section>

      <section v-show="currStep === 2" style="width: 100%">
        <DimissionTemplateDesign
          :data="formData.step2Data"
          ref="templateDesignRef"
        />
      </section>
    </main>
    <footer>
      <a-space>
        <a-button
          v-show="currStep === 2 || currStep === 3"
          @click="currStep = --currStep"
          class="btn"
          >上一步</a-button
        >
        <a-button
          type="primary"
          v-show="currStep === 1 || currStep === 2"
          @click="next"
          class="btn"
          >下一步</a-button
        >
        <a-button
          type="primary"
          v-show="currStep === 3"
          @click="save"
          class="btn"
          >保存</a-button
        >
        <a-button
          type="primary"
          v-show="currStep === 3"
          @click="submit"
          class="btn"
          >确认发起</a-button
        >
        <a-button
          type="primary"
          v-show="currStep === 3"
          @click="currStep = 1"
          class="btn"
          >跳到基本信息</a-button
        >
      </a-space>
    </footer>
  </ContentCard>
  <HumanRosterModal
    v-model:visible="humanModalVisible"
    @humanRosterEmit="humanRosterEmit"
  ></HumanRosterModal>
</template>

<script lang="ts" setup>
import { changeControlData } from '@/utils/control';
import { Message } from '@arco-design/web-vue';
import clonedeep from 'lodash.clonedeep';
import {
  GetHumanRosterList,
  GetHumanRosterDetail
} from '@/apis/management/human/humanRoster';
import {
  GetLeaveInterviewList,
  GetLeaveInterviewDetail
} from '@/apis/management/human/baseSetting/leaveSetting';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import {
  GetLeaveInterViewListDetail,
  PostLeaveInterViewListDetail,
  PutLeaveInterViewListDetail
} from '@/apis/management/human/humanChange/leave';
import DimissionTemplateDesign from './Components/TemplateDesign/index.vue';

const route = useRoute();
const router = useRouter();
const responsibleId = +localStorage.getItem('userId'); // 当前登录用户的id
const userId = +route.query.id as number; //  被面谈人id

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'intershipProofChange']);

let currStep = ref(1); // 当前步骤

let refForm = ref(); // 表单ref
// 设置步骤
const setCurrent = async (step: number) => {
  currStep.value = step;
  if (step > 1) {
    if (await refForm.value.validate()) {
      currStep.value = 1;
      return;
    }
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入模板名称'
    }
  ],
  userName: [
    {
      required: true,
      message: ''
    }
  ],
  responsibleId: [
    {
      required: true,
      message: '请选择面谈负责人'
    }
  ],
  talkTime: [
    {
      required: true,
      message: '请选择面谈时间'
    }
  ],
  talkSpace: [
    {
      required: true,
      message: '请输入面谈地点'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择离职面谈记录表模板'
    }
  ]
};

const formData = reactive({
  // 步骤1数据
  step1Data: {
    id: 0,
    name: '', // 模板名称
    userId: undefined, // 被面谈人id,
    userName: '', // 被面谈人名字
    responsibleId: undefined, // 负责人
    talkTime: '', // 面谈时间
    talkSpace: '', // 面谈地点
    templateId: undefined, // 面谈记录表id
    remark: '' // 备注,
  },
  // 步骤二数据
  step2Data: {
    id: 0,
    collections: [], // 储存控件
    companyReasons: '', // 公司原因
    peopleReasons: '', // 个人原因
    talks: [], // 面谈问题记录
    possible: 1, // 挽留可能性 1非常大 2较大 3一般 4较小 5很小
    advise: '', // 建议挽留措施
    peopleAdvise: '', // 员工对公司的建议
    summarize: '', // 面谈总结,
    userId: undefined, // 被面谈人id,
    responsibleId: undefined // 负责人
  }
});
let index = 0;
watch(
  () => formData.step1Data.templateId,
  () => {
    if (index > 0 || !formData.step1Data.id) {
      getTemplateData();
    }
    index++;
  }
);

// 获取对应离职模板信息
const getTemplateData = async () => {
  const res = await GetLeaveInterviewDetail({
    id: formData.step1Data.templateId
  });
  formData.step2Data.talks = res.takes ? clonedeep(res.takes) : [];
  console.log('====================================');
  console.log(formData.step2Data);
  console.log('====================================');
};
let humanList = ref([]), // 储存人员花名册信息
  leaveInterViewList = ref([]);

const getData = async () => {
  try {
    const [humanListRes, leaveInterViewListRes, interViewDetailRes] =
      await Promise.all([
        GetHumanRosterList({
          pageNumber: 0,
          pageSize: -1,
          typeName: '5,6'
        }),
        GetLeaveInterviewList({
          pageNumber: 0,
          pageSize: -1,
          scope: 3
        }),
        GetLeaveInterViewListDetail({
          id: userId
        })
      ]);
    humanList.value = humanListRes.content;
    leaveInterViewList.value = leaveInterViewListRes.content.filter(
      (item: any) => item.enable === 1
    );
    getInterViewData(interViewDetailRes);
    getUserInfo();
    getResponsibleInfo();
    getTemplateControlData();
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let formRef = ref();
const next = async () => {
  currStep.value = Math.min(3, currStep.value + 1);
  if (currStep.value === 1) {
    if (await refForm.value.validate()) {
      currStep.value = 1;
      return Message.error('请填写必填项');
    }
  }
};

let orginTemplateId = undefined; // 储存原始的离职模板id
const getInterViewData = (data: any) => {
  for (let i in formData.step1Data) {
    formData.step1Data[i] = data[i];
    if (i === 'templateId' && data[i] !== 0) {
      orginTemplateId = data[i];
      formData.step1Data.templateId = data[i];
    } else if (i === 'templateId' && data[i] === 0) {
      formData.step1Data.templateId = undefined;
    }
  }
  for (let i in formData.step2Data) {
    formData.step2Data[i] = data[i];
  }
};

// 获取被面谈人信息
const getUserInfo = () => {
  const tempUserInfo = humanList.value.find((item: any) => item.id === userId);
  formData.step1Data.userName = tempUserInfo?.name;
  formData.step1Data.userId = tempUserInfo?.id;
  formData.step2Data.userId = tempUserInfo?.id;
};

// 优先获取当前登录人为面谈负责人
const getResponsibleInfo = () => {
  const tempInfo = humanList.value.find(
    (item: any) => item.id === responsibleId
  );
  formData.step1Data.responsibleId = tempInfo?.id;
  formData.step2Data.responsibleId = tempInfo?.id;
};

// 获取离职控件信息
const getTemplateControlData = async () => {
  const res = await GetBusinessModalData({
    funcCode: 'SER_FUNC3803005BBBBA4640A9CEDACFB599C3C3'
  });
  formData.step2Data.collections = res?.funcCtlInfos
    ? changeControlData(res.funcCtlInfos, 'subDetail')
    : null;
  console.log(
    '🚀 ~ file: index.vue:258 ~ getTemplateControlData ~ formData.step2Data.collections:',
    formData.step2Data.collections
  );
};

let humanModalVisible = ref(false); // 是否显示花名册弹框

// 显示人员弹框
const showHumanModal = () => {
  humanModalVisible.value = true;
};

// 人员弹框返回的自定义事件
const humanRosterEmit = (record: any) => {
  formData.step1Data.responsibleId = record.id;
  formData.step2Data.responsibleId = record.id;
};

// 保存
const save = async () => {
  try {
    const temp = {
      ...formData.step1Data,
      ...formData.step2Data
    };
    if (formData.step1Data.id) await PutLeaveInterViewListDetail(temp);
    else await PostLeaveInterViewListDetail(temp);
    router.go(-1);
  } catch (error: unknown) {
    console.log(error);
  }
};

let templateDesignRef = ref(); // 步骤二组件的ref
// 确认发送
const send = async () => {
  try {
    router.go(-1);
    //
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style scoped lang="less">
.wrap {
  main {
    width: 100%;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    header {
      width: 70%;
      padding: 20px;
      margin: auto;
      border-radius: 10px;
      margin-bottom: 20px;
      box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.7);
    }

    section {
      position: relative;
      left: 50%;
      transform: translateX(-50%);
      width: 70%;

      .btn {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
      }
    }
  }
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
</style>
